import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Message {
	public String nick;
	public String text;
	public String time;
	public int checkSum;
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
			"hh:mm:ss");
	private static final String delimeter = "/0";

	public Message(String nick, String text) {
		this.nick = nick;
		this.text = text;
		this.time = dateFormat.format(new Date());
		checkSum = (int) nick.hashCode() + (int) time.hashCode()
				+ (int) text.hashCode();
	}

	public byte[] convertToByteArray() {
		StringBuilder stringBuilder = new StringBuilder(nick);
		stringBuilder.append(delimeter).append(time).append(delimeter)
				.append(text).append(delimeter);
		byte[] checkSumBytes = BigInteger.valueOf(checkSum).toByteArray();
		byte[] result = new byte[checkSumBytes.length
				+ stringBuilder.toString().getBytes().length];
		int i = 0;
		for (byte b : stringBuilder.toString().getBytes()) {
			result[i] = b;
			i++;
		}
		for (byte b : checkSumBytes) {
			result[i] = b;
			i++;
		}
		return result;
	}

	public static void checkAndPrintMessage(byte[] byteMessage, String nickName) {
		String message = null;
		try {
			message = new String(byteMessage, "ASCII");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String[] splitMessage = message.split(delimeter);
		if (splitMessage.length != 4) {
			System.out.println("Skipping wrong message");
			return;
		}
		int recievedChecksum = decodeChecksum(byteMessage, splitMessage);
		int countedChecksum = (int) splitMessage[0].hashCode()
				+ (int) splitMessage[1].hashCode()
				+ (int) splitMessage[2].hashCode();
		if (recievedChecksum != countedChecksum) {
			System.out.println("Checksum incorrect. Skipping wrong message.");
			return;
		}
		if (!splitMessage[0].equals(nickName)) {
			StringBuilder stringBuilder = new StringBuilder(splitMessage[1]);
			stringBuilder.append(" ").append(splitMessage[0]).append(":\n")
					.append(splitMessage[2]);
			System.out.println(stringBuilder.toString());
		}
	}

	public static int decodeChecksum(byte[] byteMessage, String[] splitMessage) {
		int checkStart = splitMessage[0].getBytes().length
				+ splitMessage[1].getBytes().length
				+ splitMessage[2].getBytes().length + 6;
		byte[] check = new byte[4];
		for (int i = 0; i < 4; i++) {
			check[i] = byteMessage[checkStart + i];
		}
		ByteBuffer wrapped = ByteBuffer.wrap(check);
		int recievedChecksum = wrapped.getInt();
		return recievedChecksum;
	}
}
